package com.wzqj.agent.web.controller;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.app.user.domain.UserInfo;
import com.wzqj.agent.common.JsonOutput;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.constant.WebConstant;
import com.wzqj.agent.common.env.EnvManager;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.common.exception.BusinessException;
import com.wzqj.agent.common.redis.CacheCallback;
import com.wzqj.agent.common.redis.CacheClient;
import com.wzqj.agent.common.redis.CacheKey;
import com.wzqj.agent.util.CaptchaUtil;
import com.wzqj.agent.util.SmsSOA;
import com.wzqj.agent.util.ValidateUtil;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.AgentMerchantService;
import com.wzqj.agent.web.service.AgentService;
import com.wzqj.agent.web.service.MerchantService;
import com.wzqj.agent.web.service.SalesService;
import com.wzqj.agent.web.service.UserService;
import com.wzqj.web.http.CookieUtils;
import com.wzqj.wsp.config.Config;
/**
 * 商户Web端控制层
 * @author gz
 *
 */
@Controller
@RequestMapping("/merchant")
public class MerchantWebController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private SalesService salesService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
    private CacheClient cacheClient;
	@Autowired
	private  AgentMerchantService agentMerchantService;
	
	
	@RequestMapping("/merchantList")
	public ModelAndView merchantList(
			@RequestParam(value = "phone", defaultValue = "")  String phone,
			@RequestParam(value = "mcode", defaultValue = "")  String mcode,
			HttpServletRequest request, ModelMap data){
		
		String rv = "";
		try {
			Config.getConstants().setUserToken(WebConstant.userToken_key);
			String userToken = CookieUtils.findACookieToken(request);
			Log.run.error("userToken:" + userToken);
			if (userToken==null||userToken.equals("")) {
				return new ModelAndView("/user/admin/login");
			}
			Integer userId = Integer.parseInt(userToken);
	        
			//获取用户信息
			User user  = userService.getById(userId);
			request.setAttribute("user", user);
			data.put("user", user);
			//获取用户 下的业务员信息
			Map<String, Object> params  = new HashMap<String, Object>();
			params.put("userId", userId);
			if (!StringUtils.isEmpty(phone)) {
				params.put("phone", phone);
			}
			if (!StringUtils.isEmpty(mcode)) {
				params.put("mcode", mcode);
			}
			JSONArray merchants = merchantService.merchantListPage(params);
			if (merchants!=null) {
				
				data.put("merchants", merchants);
				System.out.println("---merchants:"+merchants.toString());
			}
			rv="/user/merchant/merchantList";
			
		} catch (Exception e) {
			Log.run.error(e.getMessage());
			e.printStackTrace();
		}
		
		
		return new ModelAndView("/user/merchant/merchantList", data);
	}
	
	
	/**
	 * 跳转到门店详情
	 * @return
	 */
	@RequestMapping("toStoreInfo")
	public String toStoreInfo(){
		return "user/merchant/storeInfo";
	}
	/**
	 * 跳转到开通商户平台账户
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping("toOpen")
	public ModelAndView toOpen(ModelMap data,HttpServletRequest request){
		String rv = "";
		
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return new ModelAndView("/user/admin/login");
		}
		Integer userId = Integer.parseInt(userToken);
        
		//获取用户信息
		User user  = userService.getById(userId);
		request.setAttribute("user", user);
		data.put("user", user);
		
		rv = "/user/merchant/openMerchant";
		return new ModelAndView(rv, data);
	}
	/**
     * 获取开通商户验证码
     * @return
     */
    @RequestMapping("/captcha")
    @ResponseBody
    public JSONObject getCaptcha(String phone){

    	JSONObject data = new JSONObject();
    	
        JsonOutput output = new JsonOutput();
        if(!ValidateUtil.isMobile(phone)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        /**
         * 生成验证码
         */
        String captcha = CaptchaUtil.createCaptcha();//redis 缓存验证码有效期，5分钟
        Log.run.info("MerchantWebController#getCaptcha:验证码是：" + captcha);
        try {
            cacheClient.setex(CacheKey.开通商户验证码 + phone, 60 * 5, captcha);
        } catch (Exception e) {
            Log.run.error("MerchantWebController#getCaptcha:" + e.getMessage());
            output.setErrCode(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrCode());
            output.setMsg(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrMsg());
            return output.toJSONObject();
        }
			
        if (EnvManager.isIdc()) {
	        StringBuffer buffer = new StringBuffer();
	        buffer.append("【代理商平台】 您开通商户的验证码是：").append(captcha).append("[微智全景]");
	        boolean flag = SmsSOA.sendSms(phone, buffer.toString());
	        if(!flag){
	            output.setErrCode(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrCode());
	            output.setMsg(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrMsg());
	            return output.toJSONObject();
	        }
        }else {
        	/* data.put("captcha", captcha) ;
        	 output.setMsg("获取验证码成功");
        	 */
        	StringBuffer buffer = new StringBuffer();
	        buffer.append("【代理商平台】 您开通商户的验证码是：").append(captcha).append("[微智全景]");
	        boolean flag = SmsSOA.sendSms(phone, buffer.toString());
	        if(!flag){
	            output.setErrCode(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrCode());
	            output.setMsg(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrMsg());
	            return output.toJSONObject();
	        }
		}
        //data.put("captcha", captcha) ;
        output.setMsg("获取验证码成功");
        output.setData(data);
        return output.toJSONObject();
    }
    
    /**
     * 判断商户是否存在不存在则注册商户,返回商户资质
     * @param mobile
     * @param captcha
     * @param passlen
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public JSONObject register(HttpServletRequest req,String mobile,String captcha,Integer userId ,
    		@RequestParam(value = "passlen", defaultValue = "6")  int passlen){

        JsonOutput output = new JsonOutput();
        if(!ValidateUtil.isMobile(mobile) || !ValidateUtil.isCaptcha(captcha)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        /**
         * 校验手机验证码是否正确
         */
        Object captchaCache = cacheClient.get(CacheKey.开通商户验证码 + mobile);
        if(null == captchaCache){//验证码已过期
            output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_INVALID.getErrCode());
            output.setMsg(BusinessErrorType.LOGIN_CAPTCHA_INVALID.getErrMsg());
        }else if(!captchaCache.equals(captcha)){//验证码不正确
            output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrMsg());
        }else{//验证通过,查询或创建商户
            JSONObject data = new JSONObject();
            try {
                JSONObject merchant = merchantService.getMerchant(mobile);
                if( merchant != null ){//商户存在获取商户资质信息
                	 output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrCode());
                     output.setMsg("商户已存在");
                     return output.toJSONObject();
                    /*String id = merchant.getString("merId");
                    String uid = merchant.getString("id");
                    String nickname = merchant.getString("nickname");
                    if(StringUtils.isEmpty(id)){//用户没有资质认证
                        id = merchantService.addQualification(mobile, uid);
                    }
                    data.put("uid",uid);
                    data.put("nickname",nickname);
                    data.put("qualificationId",id);*/
                } else {//商户不存在注册商户并进行资质认证发送密码给商户
                    /**
                     * 生成随机密码发送给用户
                     */
                    String password = CaptchaUtil.generatPassword(passlen == 0 ? 6 : passlen);
                    merchant = merchantService.register(mobile, password);
                    if(merchant != null && !merchant.isEmpty()){
                        String uid = merchant.getString("id");
                        String nickname = merchant.getString("nickname");
                        StringBuffer buffer = new StringBuffer();
                        buffer.append("【微智全景】 您的商户平台登录密码是：").append(password);
                        SmsSOA.sendSms(mobile, buffer.toString());
                        String qualificationid = merchantService.addQualification(mobile, uid);
                        data.put("uid",uid);
                        data.put("nickname",nickname);
                        data.put("qualificationId",qualificationid);
                        //根据用户，保存代理商和商户之间关系
                        User user  = userService.getById(userId);
                        if (user!=null&&user.getType()==WebConstant.user_type_agent) {
                        	Integer agentId = user.getTypeId();
                        	agentMerchantService.bindMerchantToAgent(qualificationid, agentId);
                        	output.setMsg("注册商户成功");
						}
                        //List<Agent> agent = agentService.getByUser(userId);
                    }else{//用户注册失败
                        output.setErrCode(BusinessErrorType.MERCHANT_REGISTER_ERROR.getErrCode());
                        output.setMsg(BusinessErrorType.MERCHANT_REGISTER_ERROR.getErrMsg());
                    }
                }
                output.setData(data);
                output.setMsg("注册商户成功");
            } catch (BusinessException e) {
                output.setErrCode(e.getErrCode());
                output.setRetCode(e.getInnerErrCode());
                output.setMsg(e.getErrMsg());
            }
        }
        return output.toJSONObject();
    }
    /**
     * 开通商户后跳转到该商户信息和添加店铺页
     * @param request
     * @param data
     * @return
     */
    @RequestMapping("toAddStorePage")
    public ModelAndView toAddStorePage(
    		@RequestParam(value = "phone", defaultValue = "")  String phone,
    		@RequestParam(value = "qualificationId", defaultValue = "")  String qualificationId,
    		HttpServletRequest request,ModelMap data){
    	String rv = "";
    	Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return new ModelAndView("/user/admin/login");
		}
		Integer userId = Integer.parseInt(userToken);
		//获取用户信息
		User user  = userService.getById(userId);
		data.put("user", user);
		data.put("phone", phone);
		data.put("qualificationId", qualificationId);
		rv = "/user/merchant/addStore";
    	return new ModelAndView(rv,data);
    }
    
}
